package oa.web.Interceptor;

import oa.core.Constant;
import oa.core.MyCookie;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by wuwenhao on 14/10/28.
 */
public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o) throws Exception {
        Cookie cookie = MyCookie.getCookie(Constant.LOGIN_COOKIE_NAME, request);
        String nextUrl = request.getRequestURI().toString();

        //check if the url is login or the favicon.ico, then filter this
        if(nextUrl!=null && (nextUrl.equals("/login")||nextUrl.equals("/favicon.ico"))){
            return true;
        }

        //if the user's cookie is null, then add the nexturl cookie to the user, and redirect the login page
        if(cookie == null){
            Cookie nextUrlCookie = new Cookie(Constant.NEXTURL_COOKIE_NAME, nextUrl);
            nextUrlCookie.setMaxAge(Constant.COOKIE_TRANSIENT_AGE);
            nextUrlCookie.setPath(Constant.COOKIE_PATH);
            nextUrlCookie.setDomain(Constant.COOKIE_DOMAIN);
            httpServletResponse.addCookie(nextUrlCookie);
            httpServletResponse.sendRedirect("login.jsp");
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
            return;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
            return;
    }
}
